
package com.ims.iaa.html;

//
// Copyright: Metaplus & Inquiry Management Systems Ltd.  2000
//
// Author: Michael Liao 
//
import java.util.*;
import com.ims.iaa.IaaDebug;
import com.ims.iaa.URLUtil;

import java.io.*;
import java.net.*;

/**
 * This helper class provide some static method to send out HTTP request using GET or POST method
 */
public class HttpConnectionHelper
{

	/**
	 * Send request using GET method, no parameters.
	 */
	public static URLConnection sendGetRequest( URL url ) throws IOException
	{
     	return sendGetRequest( url, null, null);
	}
	
	/**
	 * Send request using GET method, with parameters.
	 */
	public static URLConnection sendGetRequest( URL url,Hashtable params, String agent ) throws IOException
	{
     	return sendGetRequest( url, params, null, agent);
	}
	/**
	 * Send request using GET method, with parameters and cookie string.
	 */
	public static URLConnection sendGetRequest( URL url, 
		Hashtable params, String cookie , String agent) throws IOException
	{
		String paramStr = ""; 
		
		if ( params != null )	{
			paramStr = "?" + toEncodedString( params );
		}

		URL newUrl = URLUtil.getURL( url.toExternalForm() + paramStr );
		URLConnection conn = newUrl.openConnection();

		conn.setUseCaches( false );

		//conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows NT; DigExt)");
		//conn.setRequestProperty("User-Agent", "Mozilla/4.74 [en] (Windows NT 5.0; U)");

		//some server won't send back ads if our user-agent havn't been set as follow.
		//for example: http://search.yahoo.com/bin/search?p=sports
		//we will get differen result by comment the following line.
		conn.setRequestProperty("User-Agent", agent);
		
		if(cookie!=null) {
			conn.setRequestProperty("Cookie",cookie);
		}
		IaaDebug.say("Start connect " + conn.getURL());
		conn.connect();
		IaaDebug.say("End connect " + conn.getURL());
		
		return conn;
	}

	/**
	 * Send request using GET method, with search strings.
	 */
	public static URLConnection sendGetRequest( String searchUrl, 
		 String cookie , String agent) throws IOException
	{

		URL newUrl = URLUtil.getURL(searchUrl);
		URLConnection conn = newUrl.openConnection();

		conn.setUseCaches( false );

		//conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows NT; DigExt)");
		//conn.setRequestProperty("User-Agent", "Mozilla/4.74 [en] (Windows NT 5.0; U)");

		//some server won't send back ads if our user-agent havn't been set as follow.
		//for example: http://search.yahoo.com/bin/search?p=sports
		//we will get differen result by comment the following line.
		conn.setRequestProperty("User-Agent", agent);
		
		if(cookie!=null) {
			conn.setRequestProperty("Cookie",cookie);
		}

		IaaDebug.say("Start connect " + conn.getURL());
		conn.connect();
		IaaDebug.say("End connect " + conn.getURL());

		return conn;
	}

	/**
	 * Send request using POST method, with no parameters.
	 */
	public static URLConnection sendPostRequest( URL url ) throws IOException
	{
		return sendPostRequest( url, null , null);
	}

	/**
	 * Send request using POST method, with parameters.
	 */
	public static URLConnection sendPostRequest( URL url, Hashtable params, String agent ) throws IOException
	{
		return sendPostRequest( url, params, null, agent );
	}
	/**
	 * Send request using POST method, with parameters and cookie string.
	 */
	public static URLConnection sendPostRequest( URL url, Hashtable params, 
			String cookie, String agent) throws IOException	{
	
		String paramStr = ""; 

		if ( params != null )	{
			paramStr = toEncodedString( params );
		}
		
		URLConnection conn = url.openConnection();

		conn.setDoInput( true );
		conn.setDoOutput( true );

		conn.setUseCaches( false );

		//conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;Windows NT; DigExt)");
		//conn.setRequestProperty("User-Agent", "Mozilla/4.74 [en] (Windows NT 5.0; U)");

		//some server won't send back ads if our user-agent havn't been set as follow.
		//for example: http://search.yahoo.com/bin/search?p=sports
		//we will get differen result by comment the following line.
		conn.setRequestProperty("User-Agent", agent);
		
		if(cookie!=null) {
			conn.setRequestProperty( "Cookie", cookie);
		}

		DataOutputStream out = new DataOutputStream( conn.getOutputStream() );
		out.writeBytes( paramStr );
		out.flush();
		out.close();
		
		return conn;
	}

	/**
	 * Convert parameters stored in the Hashtable into a single encoded string.
	 */
	private static String toEncodedString( Hashtable params )
	{
		StringBuffer strBuffer = new StringBuffer();

		for ( Enumeration names = params.keys(); names.hasMoreElements(); ) {
			String name = (String)names.nextElement();
			
			Object valueObj = params.get( name );
			if ( valueObj instanceof String ) {

				String value = (String) valueObj;
				strBuffer.append( URLEncoder.encode( name ) );
				strBuffer.append( "=" );
				strBuffer.append( URLEncoder.encode( value ) );

			} else if ( valueObj instanceof Vector ) {

				Vector values = (Vector) valueObj;
				int numOfValues=values.size();

				for ( int i=0 ; i<numOfValues; i++ ) {
					
					String value = (String) values.elementAt(i);
					strBuffer.append( URLEncoder.encode( name ) );
					strBuffer.append( "=" );
					strBuffer.append( URLEncoder.encode( value ) );
					if ( i < (numOfValues-1) ) {
						strBuffer.append( "&" );
					}
				}
			} else if ( valueObj instanceof String[] ) {

				String[] values = (String[]) valueObj;
				
				for ( int i=0; i<values.length; i++ ) {
					String value = values[i];
					strBuffer.append( URLEncoder.encode( name ) );
					strBuffer.append( "=" );
					strBuffer.append( URLEncoder.encode( value ) );
					if ( i<(values.length-1) ) {
						strBuffer.append( "&" );
					}
				}
			}
			
			if ( names.hasMoreElements() ) {
				strBuffer.append( "&" );
			}
		}
		return strBuffer.toString();
	}

	/*
	// Test driver
	public static void main( String[] args ) {
	
		RequestParameters req;
		req = new RequestParameters();
		req.put("firstName", "Smith");
		req.put("lastName","Black");
		req.put("parameters", "a+b and c");
		req.put("parameters", "bbb");
		req.put("parameters", "ccc");
		req.put("parameters", "a+b and c");
		req.put("parameters", "bbb");
		req.put("parameters", "ccc");
		IaaUtil.log( "A duplicate value parameter");
		IaaUtil.log( req );
		IaaUtil.log( toEncodedString( req.getParameter() ) );
		
		req = new RequestParameters( false );
		req.put("firstName", "Smith");
		req.put("lastName","Black");
		req.put("parameters", "a+b and c");
		req.put("parameters", "bbb");
		req.put("parameters", "ccc");
		req.put("parameters", "a+b and c");
		req.put("parameters", "bbb");
		req.put("parameters", "ccc");
		IaaUtil.log( "A non-duplicate value parameter");
		IaaUtil.log( req );
		
		IaaUtil.log( toEncodedString( req.getParameter() ) );


		req = new RequestParameters();
		req.put("p","sports");
		try {
			URL url = URLUtil.getURL("http://search.yahoo.com/bin/search");
			URLConnection conn = sendGetRequest( url, req.getParameter() );
	    	InputStream in = conn.getInputStream();
			String outFileName = "conntent.html";
			OutputStream out = new FileOutputStream( outFileName );
			IaaUtil.log("\ncontent is dumped to file: " + outFileName + "\n");
			
			byte[] buf = new byte[4096];
			int len;
			while ( ( len = in.read( buf ) ) != -1 )   {
				// dump to file
				out.write( buf, 0, len );
				// display on standard output. 
				IaaDebug.out.write( buf, 0, len );
			}
			in.close();
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	*/
} 
